// UserTableObserver.java
package com.hwpt.hwaccount.core.data;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.hwpt.hwaccount.core.base.BaseResponse;
import com.hwpt.hwaccount.core.data.local.database.UserInfoDB;
import com.hwpt.hwaccount.core.data.local.entity.UserEntity;
import com.hwpt.hwaccount.core.data.remote.api.ApiService;
import com.hwpt.hwaccount.core.data.remote.request.SyncInfoRequest;
import com.hwpt.hwaccount.core.utils.BeanUtils;
import com.hwpt.hwaccount.core.utils.CoroutineUtils;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.List;

/**
 * 全局用户表观察者，用于监听数据库users表的所有变化
 * 监听由登录成功触发，退出登录时停止
 */
public class UserTableObserver {
    private static final String TAG = "UserTableObserver";
    private static final String PREF_NAME = "UserTableObserverPrefs";
    private static final String KEY_IS_OBSERVING = "is_observing";
    private static final String KEY_IS_LOGGED_IN = "is_logged_in";

    private static UserTableObserver instance;
    private UserInfoDB database;
    private Disposable disposable;
    private boolean isObserving = false;
    private ApiService apiService;
    private Context appContext;

    private UserTableObserver(Context context) {
        this.appContext = context.getApplicationContext();
        this.database = UserInfoDB.getInstance(appContext);
    }

    public static synchronized UserTableObserver getInstance(Context context) {
        if (instance == null) {
            instance = new UserTableObserver(context.getApplicationContext());
        }
        return instance;
    }

    /**
     * 设置ApiService（依赖注入），并尝试恢复监听
     */
    public void setApiService(ApiService apiService) {
        this.apiService = apiService;
        // 设置完 ApiService 后再尝试恢复监听
        restoreObservationIfNeeded();
    }

    /**
     * 开始观察整个users表的变化（登录成功后调用）
     */
    public void startObserving() {
        if (isObserving) {
            Log.d(TAG, "已经在观察用户表");
            return;
        }

        if (apiService == null) {
            Log.e(TAG, "ApiService未初始化，无法开始观察");
            return;
        }

        isObserving = true;
        
        // 实时保存状态（每次状态变化都立即保存）
        saveRealTimeState();

        disposable = database.userDao().observeAllUsers()
                .subscribeOn(Schedulers.from(CoroutineUtils.ioExecutor()))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        users -> {
                            Log.d(TAG, "用户表发生变化，当前用户数量: " + (users != null ? users.size() : 0));
                            notifyTableChanged(users);
                        },
                        throwable -> {
                            Log.e(TAG, "观察用户表时发生错误: " + throwable.getMessage());
                            isObserving = false;
                            saveRealTimeState();
                        }
                );

        Log.d(TAG, "开始观察users表的变化");
    }

    /**
     * 停止观察用户表变化（退出登录时调用）
     */
    public void stopObserving() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
            disposable = null;
        }
        isObserving = false;
        
        // 实时保存状态
        saveRealTimeState();
        
        Log.d(TAG, "停止观察用户表");
    }

    /**
     * 检查是否正在观察
     */
    public boolean isObserving() {
        return isObserving;
    }

    /**
     * 检查用户是否已登录（根据持久化状态）
     */
    public boolean isUserLoggedIn() {
        SharedPreferences prefs = appContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        return prefs.getBoolean(KEY_IS_LOGGED_IN, false);
    }

    /**
     * 应用启动时恢复监听（如果用户已登录）
     */
    public void restoreObservationIfNeeded() {
        if (apiService == null) {
            Log.d(TAG, "ApiService未初始化，暂不恢复监听");
            return;
        }
        
        SharedPreferences prefs = appContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        boolean isLoggedIn = prefs.getBoolean(KEY_IS_LOGGED_IN, false);
        boolean shouldObserve = prefs.getBoolean(KEY_IS_OBSERVING, false);
        
        Log.d(TAG, "恢复检查: isLoggedIn=" + isLoggedIn + ", shouldObserve=" + shouldObserve);
        
        if (isLoggedIn && shouldObserve && !isObserving) {
            // 检查网络状态
            if (isNetworkAvailable()) {
                Log.d(TAG, "恢复用户表观察");
                startObserving();
            } else {
                Log.d(TAG, "网络不可用，暂不恢复观察");
            }
        }
    }

    /**
     * 实时保存状态（每次状态变化时调用）
     */
    private void saveRealTimeState() {
        new Thread(() -> {
            SharedPreferences prefs = appContext.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit()
                .putBoolean(KEY_IS_OBSERVING, isObserving)
                .putBoolean(KEY_IS_LOGGED_IN, isObserving) // 观察状态即登录状态
                .commit(); // 同步提交确保立即写入
            
            Log.d(TAG, "实时状态保存: isObserving=" + isObserving);
        }).start();
    }

    /**
     * 通知表变化
     */
    private void notifyTableChanged(List<UserEntity> users) {
        if (users != null && !users.isEmpty()) {
            UserEntity user = users.get(0);

            if (apiService == null) {
                Log.e(TAG, "ApiService未初始化，无法同步数据到远程");
                return;
            }

            SyncInfoRequest syncInfoRequest = syncUserToRemote(user);
            apiService.syncUser(syncInfoRequest).enqueue(new Callback<BaseResponse<Void>>() {
                @Override
                public void onResponse(Call<BaseResponse<Void>> call, Response<BaseResponse<Void>> response) {
                    if (response.isSuccessful()) {
                        Log.d(TAG, "同步用户成功");
                    } else {
                        Log.e(TAG, "同步用户失败: " + response.code());
                    }
                }

                @Override
                public void onFailure(Call<BaseResponse<Void>> call, Throwable t) {
                    Log.e(TAG, "同步用户失败: " + t.getMessage());
                }
            });
        }
    }

    /**
     * 清理资源
     */
    public void destroy() {
        stopObserving();
        instance = null;
    }

    private SyncInfoRequest syncUserToRemote(UserEntity user){
        SyncInfoRequest syncInfoRequest = new SyncInfoRequest();
        BeanUtils.copyProperties(user, syncInfoRequest);
        return syncInfoRequest;
    }

    /**
     * 检查网络是否可用
     */
    private boolean isNetworkAvailable() {
        try {
            ConnectivityManager cm = (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        } catch (Exception e) {
            Log.e(TAG, "检查网络状态时发生错误: " + e.getMessage());
            return false;
        }
    }
}